<template>
  <div style="padding: 20px">
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px" @keyup.enter="submitHandle()">
      <el-row>
        <el-col :span="8">
          <el-form-item prop="companyId" label="所属公司">
            <MaOrgtSelect v-model="dataForm.companyId" placeholder="请选择" @change="firmChange"></MaOrgtSelect>
          </el-form-item>
          <el-form-item label="设备imei" prop="imei">
            <el-select
              v-model="dataForm.imei"
              filterable
              allow-create
              remote
              :disabled="props.imei !== 'undefined'"
              :remote-method="remoteMethod"
              :loading="inputLoading"
              placeholder="请选择">
              <el-option v-for="item in imeiList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item prop="status" label="是否可用">
            <el-checkbox v-model="dataForm.status" :true-value="1" :false-label="0"></el-checkbox>
          </el-form-item>
          <el-form-item prop="canLogin" label="允许登录">
            <el-checkbox v-model="dataForm.canLogin"></el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label=" "></el-form-item>
          <el-form-item prop="groupId" label="所属分组">
            <el-select
              v-model="dataForm.groupId"
              placeholder="请选择设备类型"
              clearable
              @clear="() => (dataForm.groupId = '')">
              <el-option v-for="item in equipmentList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="图标" prop="icon">
            <img
              :src="`${constant.iconUrl}${dataForm.icon}/green.png`"
              style="width: 30px; height: 30px; margin-right: 10px"
              alt="" />
            <el-popover ref="popover" placement="bottom" :width="400" trigger="click">
              <template #reference>
                <el-button class="m-2" size="small" @click="visible = true">选择图标</el-button>
              </template>
              <el-radio-group
                v-model="dataForm.icon"
                style="display: flex; justify-content: flex-start; flex-wrap: wrap"
                @change="radioChange">
                <el-radio
                  v-for="item in carTypeList"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  style="padding: 10px 0">
                  <div style="display: flex; align-items: center">
                    <img
                      :src="`${constant.iconUrl}${item.dictValue}/green.png`"
                      style="width: 30px; height: 30px"
                      alt="" />
                    <p>{{ item.dictLabel }}</p>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-popover>
          </el-form-item>
          <el-form-item label="登录密码" prop="password">
            <el-input v-model="dataForm.password" placeholder="登录密码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label=" "></el-form-item>
          <el-form-item label="设备类型" prop="productId">
            <el-select v-model="dataForm.productId" placeholder="请选择设备类型">
              <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.deviceDesc" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建日期" prop="platformStartDate">
            <el-date-picker
              v-model="dataForm.platformStartDate"
              disabled
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="创建日期" />
          </el-form-item>
          <el-form-item label="过期日期" prop="platformEndDate">
            <el-date-picker
              v-model="dataForm.platformEndDate"
              :disabled="props.name === '车辆信息'"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="过期日期" />
          </el-form-item>
        </el-col>
        <el-form-item v-if="switchButton" label="批量加设备">
          <el-switch v-model="value1" />
        </el-form-item>
      </el-row>
      <div v-if="!value1">
        <el-row>
          <el-col :span="8">
            <el-form-item label="自定义编号" prop="devNo">
              <el-input v-model="dataForm.devNo" placeholder="设备自定义编号"></el-input>
            </el-form-item>
            <el-form-item label="司机名字" prop="driverName">
              <el-input v-model="dataForm.driverName" placeholder="司机名字"></el-input>
            </el-form-item>
            <el-form-item label="SIM" prop="sim">
              <el-input v-model="dataForm.sim" placeholder="SIM"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备名称" prop="plateNo">
              <el-input v-model="dataForm.plateNo" placeholder="设备名称"></el-input>
            </el-form-item>
            <el-form-item label="司机手机号" prop="driverPhone">
              <el-input v-model="dataForm.driverPhone" placeholder="司机手机号"></el-input>
            </el-form-item>
            <el-form-item label="ICCID" prop="iccid">
              <el-input v-model="dataForm.iccid" placeholder="ICCID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车辆Vin" prop="carVin">
              <el-input v-model="dataForm.carVin" placeholder="车辆Vin"></el-input>
            </el-form-item>
            <el-form-item label=" "></el-form-item>
            <el-form-item prop="lockSim" label="锁定SIM卡">
              <el-checkbox v-model="dataForm.lockSim"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="自定义备注" prop="remark">
          <el-input v-model="dataForm.remark" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
        </el-form-item>
        <el-form-item label="视频路数" prop="jt1078Avch">
          <el-input-number v-model="dataForm.jt1078Avch" type="number" :min="0" />
        </el-form-item>
      </div>
      <div v-else>
        <el-row>
          <el-col :span="12">
            <el-form-item label="序号长度" prop="length">
              <el-input-number v-model="length" :min="8" :max="18" />
            </el-form-item>
            <el-form-item label="设备序号" prop="imei">
              <el-input v-model="dataForm.imei" :autosize="{ minRows: 2, maxRows: 5 }" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div style="margin-left: 100px">
              <el-input style="width: 250px; height: 150px" disabled placeholder="">
                <template #prefix="scope">
                  <div v-show="dataForm.imei" class="display" :class="dataForm.imei.length > length ? 'red' : ''">
                    <span v-show="dataForm.imei.length > length" class="display">
                      <span>有误序号：1</span>
                      <span>错误原因：设备序号不是数字或者字母或者长度不一致</span>
                    </span>
                    <div class="display" :class="dataForm.imei.length > length ? 'red' : 'green'">
                      <span>录入总数：1</span>
                      <span>设备列表：{{ dataForm.imei }}</span>
                    </div>
                  </div>
                </template>
              </el-input>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <el-table v-if="dataForm.jt1078Avch !== 0" :data="dataList" border class="layout-table">
      <el-table-column prop="id" label="通道" header-align="center" align="center" width="100"></el-table-column>
      <el-table-column prop="" label="名称" header-align="center" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.name" placeholder="自定义"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="canLogin" label="是否启用" header-align="center" align="center">
        <template #default="scope">
          <el-radio-group v-model="scope.row.enlbe">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 30px auto; text-align: center">
      <el-button @click="emits('Close')">取消</el-button>
      <el-button type="primary" @click="submitHandle()">确定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus/es'
import {
  getdeviceGroupingApi,
  getlistGroupingApi,
  useDeviceApi,
  useDeviceSaveSubmitApi,
  useSearchImeiApi
} from '@/api/gps/device'
import { getProductByUser } from '@/api/gps/product'
import {
  ElCheckbox,
  ElButton,
  ElCol,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElOption,
  ElRadio,
  ElRadioGroup,
  ElRow,
  ElSelect,
  ElSwitch,
  ElTable,
  ElPopover,
  ElTableColumn
} from 'element-plus'
import MaOrgtSelect from '@/components/ma-org/ma-org-select/index.vue'
import { useAppStore } from '@/store/modules/app'
import constant from '@/utils/constant'
import { gpsbus } from '@/utils/gps/event'

const emits = defineEmits(['Close'])

let update = true
const popover = ref()
const visible = ref(false)
const dataFormRef = ref()
const dataList = ref<any[]>([])
const imeiList = ref<any[]>([])
const deviceTypeList = ref()
const equipmentList = ref()
const inputLoading = ref(false)
const disabled = ref(true)
const switchButton = ref(true)
const dataForm = reactive({
  imei: '',
  devNo: '',
  sim: '',
  iccid: '',
  simStartDate: '',
  simEndDate: '',
  platformStartDate: '',
  lockSim: true,
  platformEndDate: '',
  protocol: '',
  productId: '',
  plateNo: '',
  // vehicleColor: '',
  carVin: '',
  driverName: '',
  driverPhone: '',
  companyId: undefined,
  groupId: '',
  jt1078Avch: 0,
  canLogin: true,
  password: '',
  remark: '',
  // deviceType: '',
  status: 1,
  isTest: true,
  icon: 'car',
  // avatar: '',
  // fromGnssId: '',
  // crtUserId: '',
  // crtTime: '',
  // updateUserId: '',
  // updateTime: '',
  // attribute: undefined,
  jt1078Avset: ''
})
const props = defineProps({
  imei: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: true
  }
})

watch(
  () => dataForm.jt1078Avch,
  (val) => {
    dataList.value = []
    for (let i = 1; i <= dataForm.jt1078Avch; i++) {
      dataList.value.push({ id: i, name: '', enlbe: 1 })
    }
  }
)

const appStore = useAppStore()
//自己定义的
const value1 = ref(false)
const length = ref(8)
function remoteMethod(query: string) {
  if (query) {
    inputLoading.value = true
    useSearchImeiApi(query).then((res) => {
      inputLoading.value = false
      imeiList.value = res.data
    })
  } else {
    imeiList.value = []
  }
}
const carTypeList = computed(() => {
  return appStore.getDictTypeList('car_icon')
})

function radioChange() {
  popover.value?.hide()
}

//获取设备
function EquipmentList() {
  getProductByUser().then((res) => {
    deviceTypeList.value = res.data
  })
}
const getDevice = () => {
  EquipmentList()
  useDeviceApi(props.imei).then((res) => {
    if (!res.data.icon) {
      res.data.icon = 'car'
    }
    Object.assign(dataForm, res.data)
    // @ts-ignore
    dataForm.companyId = parseInt(dataForm.companyId)
    getDeviceGrouping(dataForm.groupId)
    dataList.value = []
    analysis(dataForm.jt1078Avset)
  })
}
props.imei !== 'undefined' ? getDevice() : EquipmentList()

const dataRules = ref({
  imei: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  companyId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})
//解析字符串
function analysis(str) {
  if (!str) {
    return
  }
  const data = str.split('|')
  dataList.value = data.map((item, index) => {
    return {
      id: index++,
      name: item === '*' ? '' : item,
      enlbe: item === '*' ? 0 : 1
    }
  })
}

function firmChange() {
  getDeviceGrouping()
}

//设备分组
function getDeviceGrouping(groupId?) {
  dataForm.groupId = ''
  getdeviceGroupingApi(dataForm.companyId).then((res) => {
    equipmentList.value = res.data
    disabled.value = false
  })
  dataForm.groupId = groupId ? groupId : ''
}
//转换字符串
function conversion(list) {
  if (list.length === 0) {
    return
  }
  let data = list.map((item, index) => {
    if (item.enlbe !== 1) {
      return '*'
    } else if (list[index].name) {
      return list[index].name
    } else {
      return ++index
    }
  })
  dataForm.jt1078Avset = data.join('|')
}
// 表单提交
const submitHandle = () => {
  update = props.imei === 'undefined'
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false
    }
    useDeviceSaveSubmitApi(dataForm, update).then(() => {
      ElMessage.success({
        message: '操作成功',
        duration: 500,
        onClose: () => {
          emits('Close')
          if (props.imei) {
            gpsbus.emit('repaint', { nodeId: 'd-' + props.imei, icon: dataForm.icon })
          }
        }
      })
    })
  })
}
</script>
<style scoped>
span {
  display: inline-block;
  font-size: 10px;
}
.display {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-items: baseline;
}
.red {
  color: red;
}
.green {
  color: green;
}
</style>
